package lc.q101_150;

import java.util.Arrays;

public class Q134 {

    public int canCompleteCircuit(int[] gas, int[] cost) {
        boolean[] flags = new boolean[gas.length];
        Arrays.fill(flags, true);
        for (int i = 0; i < gas.length; ) {
            int remainGas = 0;
            boolean flag = true;
            // 如果从i出发，到不了j节点，那么从i+1...j出发都到不了j节点
            int j = i;
            for (int k=0; k < gas.length;k++) {
                remainGas = remainGas + gas[j];
                if (remainGas < cost[j]) {
                    flag = false;
                    break;
                }
                remainGas = remainGas - cost[j];
                j = (j + 1) % gas.length;
            }
            if (flag) {
                return i;
            } else {
                flags[i] = false;
                i = (j + 1) % gas.length;
                if (!flags[i]) {
                    return -1;
                }
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Q134 q134 = new Q134();
        System.out.println(q134.canCompleteCircuit(new int[]{1,2,3,4,5}, new int[]{3,4,5,1,2}));
        System.out.println(q134.canCompleteCircuit(new int[]{2,3,4}, new int[]{3,4,3}));
    }
}
